const service = require('../../../service/port.js')
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const uploadImage = require('../../../utils/uploadImg/uploadImg.js')
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    unpayList: [],
    unreviceList: [],
    completeList: [],
    closerList: [],
    refundList: [],
    status: 1, //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败
    pageSize: 4,
    pageNum: 1,
    noData: false, // 是否有更多数据    
    cancelOrdershow: false, //取消订单 默认不显示
    radio: 1, //取消订单
    currentstatus: '', // 公用
    orderId: '', // 公用
    canclevalue: '', //取消原因
    showrefundsbtn: '', //申请退款
    refundShow: false,
    returnReson: '',
    refundarray: ['已收货', '未收货'],
    fileList: [],
    refundprogressShow: false,
    resons: '', //退款进度 退款原因
    images: [], //退款进度 品正图片
    returnMoney: '',
    currentOrder: '',
    returnCreateTime: '',
    appStu: 0, //审批状态 0待审批 1 同意 2拒绝
    appResult: '',
    returnModifyTime: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  getList(callback) {
    let customerId = wx.getStorageSync('userInfo').id;
    service.getTbOrderList({
      "tbOrder": {
        "customerId": customerId, //客户id
        "status": this.data.status
      },
      "queryRequest": {
        "pageSize": this.data.pageSize,
        "pageNum": this.data.pageNum
      }
    }, res => {
      // console.log(res)
      callback(res)
    })


  },
  onLoad: function (options) {
    console.log(options)

    var self = this;
    /**
     * 获取当前设备的宽高
     */
    wx.getSystemInfo({
      success: function (res) {
        self.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
    // 订单列表
    wx.showLoading({
      title: '加载中...',
    })
    if (options) {
      if (options.index == '1') {
        this.setData({
          currentTab: 1,
          status: "2,3"
        })
        this.getList(function (res) {
          console.log(res)
          if (res.data.rows.length == 0) {
            self.setData({
              noData: true,
            })
          } else {
            self.setData({
              unreviceList: res.data.rows,
              winHeight: res.data.rows.length * 250
            })
            wx.hideLoading()
          }

        })
      } else if (options.index == '2') {
        this.setData({
          currentTab: 2,
          status: "4"
        })
        this.getList(function (res) {
          console.log(res)
          if (res.data.rows.length == 0) {
            self.setData({
              noData: true,
            })
          } else {
            self.setData({
              completeList: res.data.rows,
              winHeight: res.data.rows.length * 240
            })
            wx.hideLoading()
          }

        })
      } else {
        this.getList(function (res) {
          console.log(res)
          if (res.data.rows.length == 0) {
            self.setData({
              noData: true,
            })
          } else {
            self.setData({
              unpayList: res.data.rows,
              winHeight: res.data.rows.length * 240
            })
            wx.hideLoading()
          }

        })
      }
    }


  },
  //  tab切换逻辑
  swichNav: function (e) {
    var self = this;
    this.data.noData = false;
    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      self.setData({
        currentTab: e.target.dataset.current,
        pageNum: 1
      })
    }
  },
  //内容切换
  bindChange: function (e) {
    console.log(e)
    var self = this;
    if (e.detail.current == 0) {
      this.data.status = "1"
      this.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          self.setData({
            unpayList: res.data.rows,

            winHeight: res.data.rows.length * 250
          })
        }
      })
    } else if (e.detail.current == 1) {
      this.data.status = "2,3"
      this.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          self.setData({
            unreviceList: res.data.rows,

            winHeight: res.data.rows.length * 250
          })
        }
      })
    } else if (e.detail.current == 2) {
      this.data.status = "4"
      this.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          self.setData({
            completeList: res.data.rows,

            winHeight: res.data.rows.length * 250
          })
        }
      })
    } else if (e.detail.current == 3) {
      this.data.status = "5"
      this.getList(function (res) {
        console.log(res)
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          self.setData({
            closerList: res.data.rows,
            winHeight: res.data.rows.length * 250
          })
        }
      })
    } else if (e.detail.current == 4) {
      this.data.status = "7,8,9"
      this.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          self.setData({
            refundList: res.data.rows,

            winHeight: res.data.rows.length * 250
          })
        }
      })
    }
    self.setData({
      currentTab: e.detail.current
    });

  },
  payButton: function (e) {
    console.log(e)
    service.payment({
      "orderNum": e.currentTarget.dataset.index.orderNum, //订单编号
      "actualPay": this.data.orderinfo.actualPay, //res.data.actualPay//实付金额。单位:分。如:20007，表示:200元7分
      "title": e.currentTarget.dataset.index.title,
      "openid": wx.getStorageSync('userInfo').openId,
    }, res1 => {
      console.log(res1)
      wx.requestPayment({
        appId: res1.data.appId,
        timeStamp: res1.data.timeStamp,
        nonceStr: res1.data.nonceStr,
        package: res1.data.package,
        signType: res1.data.signType,
        paySign: res1.data.sign,


        success(res) {
          Toast.success('支付成功');

        },
        fail(res) {
          console.log(res);
          Toast.fail('支付失败');
        }
      })
    })
  },
  cancelOrder: function (e) {
    console.log(e)
    this.setData({
      cancelOrdershow: true,
      currentstatus: e.currentTarget.dataset.index.status,
      orderId: e.currentTarget.dataset.index.id
    })
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  onClose: function () {
    this.setData({
      cancelOrdershow: false,
      radio: ''
    })
  },
  onClick(event) {
    const {
      name
    } = event.currentTarget.dataset;
    this.setData({
      radio: name,
    });
  },
  getcanclevalue: function (e) {
    this.setData({
      canclevalue: e.detail.value,
    });
  },
  //取消订单
  cancleButton: function (e) {
    const self = this
    service.cancleTbOrder({
      "orderId": this.data.orderId, //订单标识
      "status": "5", //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败
      "reason": this.data.radio, //取消原因
      "other": this.data.canclevalue, //其他原因
      "orderDetailId": "",
      "type": "0" //退款类型 0订单退款 1 单商品退款
    }, function (res) {
      wx.showToast({
        title: '成功',
        icon: 'success',
        duration: 2000
      })
      self.setData({
        cancelOrdershow: false,
        radio: '',
        canclevalue: '',
        noData: false,
        pageSize: 4,
        pageNum: 1
      });
      if (self.data.status == "1") {
        self.getList(res => {
          self.setData({
            unpayList: res.data.rows,
          })
        })
        self.onLoad()
      } else if (self.data.status == "2,3") {
        self.getList(res => {
          self.setData({
            unreviceList: res.data.rows,
          })
        })
        self.onLoad()
      } else if (self.data.status == "4") {
        self.getList(res => {
          self.setData({
            completeList: res.data.rows,
          })
        })
        self.onLoad()
      } else if (self.data.status == "5") {
        self.getList(res => {
          self.setData({
            closerList: res.data.rows,
          })
        })
        self.onLoad()
      } else if (self.data.status == "7,8,9") {
        self.getList(res => {
          self.setData({
            refundList: res.data.rows,
          })
        })
        self.onLoad()
      }
    })
  },
  //删除订单
  deletelOrder: function (e) {
    console.log(e)
    Dialog.confirm({
        title: '提示',
        message: '确认删除该订单吗？',
      })
      .then(() => {
        // on confirm
        const self = this
        service.cancleTbOrder({
          "orderId": e.currentTarget.dataset.index.id, //订单标识
          "status": "10" //状态,1、未付款 2、已付款,未发货 3、已发货,未确认 4、交易成功5、交易关闭 6、已评价7、退货中 8、退货成功,9退货失败 10 删除订单
        }, function (res) {
          self.setData({
            pageSize: 4,
            pageNum: 1
          });
          if (self.data.status == "1") {
            self.getList(res => {
              self.setData({
                unpayList: res.data.rows,
              })
            })
            self.onLoad()
          } else if (self.data.status == "2,3") {
            self.getList(res => {
              self.setData({
                unreviceList: res.data.rows,
              })
            })
            self.onLoad()
          } else if (self.data.status == "4") {
            self.getList(res => {
              self.setData({
                completeList: res.data.rows,
              })
            })
            self.onLoad()
          } else if (self.data.status == "5") {
            self.getList(res => {
              self.setData({
                closerList: res.data.rows,
              })
            })
            self.onLoad()
          } else if (self.data.status == "7,8,9") {
            self.getList(res => {
              self.setData({
                refundList: res.data.rows,
              })
            })
            self.onLoad()
          }
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
        })
      })
      .catch(() => {
        // on cancel
      });



  },
  //申请退款按钮显示 隐藏
  togglebtn1: function (e) {
    console.log(e)
    let index = e.currentTarget.dataset.index.id
    if (this.data.showrefundsbtn == index) {
      this.setData({
        showrefundsbtn: false
      })
    } else {
      this.setData({
        showrefundsbtn: index
      })
    }



  },
  //申请退款
  applyRefund: function (e) {
    //console.log(e)
    this.setData({
      refundShow: true,
      cash: e.currentTarget.dataset.index.actualPay,
      currentOrder: e.currentTarget.dataset.index.id
    })
  },
  //
  refundClose: function (e) {
    this.setData({
      refundShow: false
    })
  },
  //
  //退款图片
  afterRead: function (e) {

    var list = this.data.fileList;
    list.push({
      url: e.detail.file.path
    })
    this.setData({
      fileList: list
    })
    console.log(this.data.fileList);
  },
  deletephoto: function (event) {
    const {
      index,
      name
    } = event.detail;
    const fileList = this.data.fileList;
    fileList.splice(index, 1);
    this.setData({
      fileList: fileList
    })

  },

  refundButton: function (e) {

  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },
  //退款原因
  getreturnReson: function (e) {
    this.setData({
      returnReson: e.detail.value
    })
  },
  progressShow: function (e) {
    console.log(e)
    let imagedata = e.currentTarget.dataset.index.images.split(",")
    this.setData({
      refundprogressShow: true,
      resons: e.currentTarget.dataset.index.returnReson,
      returnMoney: e.currentTarget.dataset.index.actualPay,
      images: imagedata,
      returnCreateTime: e.currentTarget.dataset.index.returnCreateTime,
      appStu: e.currentTarget.dataset.index.appStu, //审批状态 0待审批 1 同意 2拒绝
      appResult: e.currentTarget.dataset.index.appResult,
      returnModifyTime: e.currentTarget.dataset.index.returnModifyTime,

    })
  },
  //退款进度
  progressClose: function (e) {
    this.setData({
      refundprogressShow: false
    })
  },
  //查看物流
  checklogistic: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index.id
    wx.navigateTo({
      url: '/pages/order/logistics/index?id=' + index,
    })
  },
  //确认收货
  confirmOrder: function (e) {

    Dialog.confirm({
        title: '提示',
        message: '确认收货吗？',
      })
      .then(() => {
        // on confirm
        const self = this
        service.confirmReceipt({
          "orderId": e.currentTarget.dataset.index.id, //订单标识       
        }, function (res) {
          if (self.data.status == "1") {
            self.getList(res => {
              self.setData({
                unpayList: res.data.rows,
              })
            })
          } else if (self.data.status == "2,3") {
            self.getList(res => {
              self.setData({
                unreviceList: res.data.rows,
              })
            })
          } else if (self.data.status == "4") {
            this.getList(res => {
              self.setData({
                completeList: res.data.rows,
              })
            })
          } else if (self.data.status == "5") {
            this.getList(res => {
              self.setData({
                closerList: res.data.rows,
              })
            })
          } else if (self.data.status == "7,8,9") {
            this.getList(res => {
              self.setData({
                refundList: res.data.rows,
              })
            })
          }
          wx.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 2000
          })
        })
      })
      .catch(() => {
        // on cancel
      });

  },

  //跳转到订单详情
  productdetail: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index.id
    wx.navigateTo({
      url: '/pages/order/orderDetail/index?id=' + index,
    })

  },

  confirmRefund: function () {
    // for (var i = 0; i < this.data.fileList.length; i++) {
    //   //显示消息提示框


    //   //上传图片
    //   //你的域名下的/images/当前年月日文件下的/图片.png
    //   //图片路径可自行修改【(这二个参数就是你oss地址目录的下一个路径目录，比如:https://xxx.com/images/xxx.png)】
    //   uploadImage(this.data.fileList[i].url, 'images/',
    //     function (result) {
    //       console.log("======上传成功图片地址为：", result);
    //       //这个result就是返给你上传到oss上的地址链接
    //       wx.hideLoading();
    //     }, function (result) {
    //       console.log("======上传失败======", result);

    //       wx.hideLoading()
    //     }
    //   )
    // }
    var self = this;
    wx.showLoading({
      title: '正在上传图片',
      mask: true
    })
    var imglist = []

    function uploadimg() {
      if (self.data.fileList.length > 0) {
        var imgpath = self.data.fileList.pop();
        uploadImage(imgpath.url, 'images/',
          function (result) {
            console.log("======上传成功图片地址为：", result);
            imglist.push(result)
            //这个result就是返给你上传到oss上的地址链接
            uploadimg()
          },
          function (result) {
            console.log("======上传失败======", result);
            Toast.fail('上传失败');

            uploadimg()
          }
        )

      } else {

        service.applyRefund({
          "orderId": self.data.currentOrder, //订单标识
          "returnReson": self.data.returnReson, //退货原因
          "images": imglist.toString(), //凭证图片
          "appcustomerId": wx.getStorageSync('userInfo').id, //审批人标识
          "orderDetailId": "574",
          "type": "1" //退款类型 0订单退款 1 单商品退款
          // "refundAmount":

        }, res => {

          console.log(res)
          self.getList(function (res) {

            console.log(res)

            if (self.data.status == "2,3") {
              if (res.data.rows.length == 0) {
                self.setData({
                  noData: true,
                })
              } else {
                self.setData({
                  unreviceList: res.data.rows,
                  winHeight: res.data.rows.length * 250
                })
                wx.hideLoading()
              }
            } else if (self.data.status == "4") {
              if (res.data.rows.length == 0) {
                self.setData({
                  noData: true,
                })
              } else {
                self.setData({
                  completeList: res.data.rows,
                  winHeight: res.data.rows.length * 250
                })
                wx.hideLoading()
              }

            }






          })
          self.setData({
            refundShow: false
          })
          Toast.success('申请成功');
          wx.hideLoading();
        })

      }
    }
    uploadimg();

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  stopTouchMove: function () {
    return false;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 请求数据
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.setData({
      pageNum: 1,
      noData: false
    })
    const self = this
    if (this.data.status == "1") {
      this.getList(function (res) {
        self.setData({
          unpayList: res.data.rows,
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "2,3") {
      this.getList(function (res) {
        self.setData({
          unreviceList: res.data.rows,
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "4") {

      this.getList(function (res) {
        self.setData({
          completeList: res.data.rows,
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "5") {
      this.getList(function (res) {
        self.setData({
          closerList: res.data.rows,
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "7,8,9") {
      this.getList(function (res) {
        self.setData({
          refundList: res.data.rows,
        })
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    }

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 判读数据是否加载完毕
    if (this.data.noData) return
    // 停止下拉刷新
    wx.stopPullDownRefresh();
    wx.showNavigationBarLoading() //在标题栏中显示加载
    const unpayList = this.data.unpayList
    const unreviceList = this.data.unreviceList
    const completeList = this.data.completeList
    const closerList = this.data.closerList
    const refundList = this.data.refundList
    let pageNum = this.data.pageNum
    this.setData({ // 每次下拉 page+1
      pageNum: ++pageNum
    })
    const self = this
    if (this.data.status == "1") {
      self.getList(function (res) {
        console.log(res)
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          res.data.rows.forEach(item => {
            unpayList.push(item)
          })
          let height = unpayList.length;

          self.setData({
            unpayList: unpayList,
            winHeight: height * 250
          })
        }
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "2,3") {

      self.getList(function (res) {

        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          res.data.rows.forEach(item => {
            unreviceList.push(item)
          })
          console.log(unreviceList.length)

          let height = unreviceList.length;
          self.setData({
            unreviceList: unreviceList,
            winHeight: height * 250
          })
        }
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "4") {

      self.getList(function (res) {
        console.log(res)
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          res.data.rows.forEach(item => {
            completeList.push(item)
          })
          let height = completeList.length;
          self.setData({
            completeList: completeList,
            winHeight: height * 250
          })

        }
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "5") {
      self.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          res.data.rows.forEach(item => {
            closerList.push(item)
          })
          let height = closerList.length;
          self.setData({
            closerList: closerList,
            winHeight: height * 250
          })
        }
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    } else if (this.data.status == "7,8,9") {
      self.getList(function (res) {
        if (res.data.rows.length == 0) {
          self.setData({
            noData: true
          })
        } else {
          res.data.rows.forEach(item => {
            refundList.push(item)
          })
          let height = refundList.length;
          self.setData({
            refundList: refundList,
            winHeight: height * 250
          })
        }
        wx.hideNavigationBarLoading()
        wx.stopPullDownRefresh();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})